<template>

	<view class="container">
		<!-- 状态栏 statusBar用于控制app是否状态栏沉浸 true为显示状态栏和导航栏-->
		<view class="box-bg">
			<uni-nav-bar :statusBar="true" :shadow="true" :border="false" left-icon="left" title="购物车"
				@clickLeft="back" />
		</view>
		<!-- 空白页 -->
		<view v-if="empty===true" class="empty">
			<!-- <image src="/static/emptyCart.jpg" mode="aspectFit"></image> -->
			<view class="empty-tips">
				空空如也
			</view>
		</view>
		<view v-else>
			<!-- 商品列表 -->
			<view class="cart-list">
				<scroll-view :scroll-top="0" scroll-y="true" class="scroll-Y" @scrolltoupper="upper"
					@scrolltolower="lower" @scroll="scroll">
					<block v-for="(item, index) in cartList" :key="item.id">
						<view class="cart-item" :class="{'b-b': index!==cartList.length-1}">
							<radio class="checkbox" :checked="item.checked" color="#000000"
								:class="{checked: item.checked}" @click="check(item)" />
							<view class="image-wrapper">
								<image :src="item.image" class="image-loaded" mode="aspectFit" lazy-load
									@error="onImageError(item)"></image>
							</view>
							<view class="item-right">
								<text class="clamp title">{{item.title}}</text>
								<text class="attr">{{item.attr_val}}</text>
								<text class="price">¥{{item.price}}</text>
								<uni-number-box class="step" :min="1" :max="item.stock"
									:value="item.joining_number>item.stock?item.stock:item.joining_number"
									:isMax="item.joining_number>=item.stock||!item.checked?true:false" :isMin="item.joining_number<=1"
									:index="index" @eventChange="numberChange"></uni-number-box>
							</view>
							<text @click="deleteCartItem(index)">×</text>
						</view>
					</block>
				</scroll-view>
			</view>
			<!-- 底部菜单栏 -->
			<view class="action-section">
				<view class="checkbox">
					<label :style="{'display': 'flex',
									'align-items': 'center',
									}">
						<radio :checked="allChecked" color="#000000" @click="check('all')" />全选
					</label>
				</view>
				<view class="total-box">
					<text class="price">¥{{total}}</text>
					<text class="coupon">
						已优惠
						<text>74.35</text>
						元
					</text>
				</view>
				<button type="primary" class="no-border confirm-btn" @click="createOrder">结算{{text}}</button>
			</view>
		</view>
	</view>
</template>


<script>
	import uniNumberBox from '@/components/uni-number-box.vue'
	import {
		_findProduct
	} from '@/service/shop.js'
	import {
		_deleteByProduct
	} from '@/service/shop.js'
	import {
		_findCommodity
	} from '@/service/shop.js'
	export default {
		components: {
			uniNumberBox
		},
		data() {
			return {
				total: 0, //总价格
				allChecked: false, //全选状态  true|false
				userAccount: null, //用户账号(手机号),同后端account_user
				empty: false, //空白页现实  true|false
				cartList: [], //这个list只是记录了购物车里商品的种类
				num: 0, //商品数量
				text: "" //结算处文字显示
			};
		},
		onLoad(options) {
			console.log('🛒 购物车页面加载，参数:', options);
			
			uni.showLoading({
				title: "请稍后"
			});
			
			// 从URL参数获取用户账号
			this.userAccount = options.userAccount;
			console.log('👤 用户账号:', this.userAccount);
			
			// 如果URL参数中没有用户账号，尝试从本地存储获取
			if (!this.userAccount) {
				try {
					const userInfo = uni.getStorageSync('userInfo');
					if (userInfo && userInfo.accountNum) {
						this.userAccount = userInfo.accountNum;
						console.log('👤 从本地存储获取用户账号:', this.userAccount);
					} else {
						console.warn('⚠️ 未找到用户账号');
					}
				} catch (e) {
					console.error('❌ 读取用户信息失败:', e);
				}
			}
			
			let self = this,
				localData = {};
			self.getCartData().
			then(function(data) {
				console.log('📦 购物车原始数据:', data);
				if (data.length == 0) {
					console.log('ℹ️ 购物车为空');
					uni.hideLoading();
					self.cartList = [];
					return;
				}
				
				let processedCount = 0;
				data.forEach(obj => {
					self.getCommodityData(obj.serialnum_commodity).
					then(result => {
						localData[obj.serialnum_commodity] = result; //重写购物车商品信息
						processedCount++;
						console.log(`✅ 已处理 ${processedCount}/${data.length} 个商品`);
						
						if (processedCount === data.length) { //当所有商品信息获取完毕
							console.log('✅ 所有商品信息获取完成，初始化购物车');
							self.init(localData);//初始化购物车商品列表
						}
					}).catch(error => {
						console.error('❌ 获取商品详情失败:', obj.serialnum_commodity, error);
						processedCount++;
						if (processedCount === data.length) {
							self.init(localData);
						}
					})
				})
			}).catch(function(error) {
				console.error('❌ 获取购物车数据失败:', error);
				uni.hideLoading();
				uni.showToast({
					title: '加载失败',
					icon: 'error',
					duration: 2000
				});
			});
		},
		watch: {
			//显示空白页
			cartList(e) {
				let empty = e.length === 0 ? true : false;
				if (this.empty !== empty) {
					this.empty = empty;
				}
			},
			//商品数量变化时触发
			num() {
				if (this.num > 0) {
					this.text = `(${this.num})`;
				} else {
					this.text = '';//修改结算字体
				}
				this.calcTotal(); //计算总价
			}
		},
		methods: {
			// 根据商品名称获取对应的图片路径
			getProductImage(name_commodity) {
				if (!name_commodity) {
					return "../../static/images/51276e00a4890f11936fcc00b81e6367.png";
				}
				
				// 创建商品名称与图片的映射关系
				const productImageMap = {
					'箱式加热炉': '../../static/images/xiangshijiarelu.jpg',
					'柜式加热炉': '../../static/images/guishijiarelu.jpg',
					'搅拌器': '../../static/images/jiaobanji.jpg',
					'家用搅拌器': '../../static/images/shiyanyongfensuiji.jpg',
					'锐牌粉碎机': '../../static/images/ruipaijiaobanji.jpg',
					'粉碎机': '../../static/images/fensuiji.jpg'
				};
				
				// 检查商品名称是否包含映射表中的关键词
				for (const productType in productImageMap) {
					if (name_commodity.includes(productType)) {
						return productImageMap[productType];
					}
				}
				
				// 如果不匹配任何特定产品类型，使用默认图片
				return "../../static/images/51276e00a4890f11936fcc00b81e6367.png";
			},
			
			async init(localData) {
				let self = this;
				this.getCartData().
				then(function(data) {
					for (let i = 0; i < data.length; ++i) {
						data[i].checked = false; //初始化商品选中状态
						console.log('购物车商品数据:', data[i])
						if (localData[data[i].serialnum_commodity]) { //这边比较敏感，容易unfinded，所以加一个判断
							const commodityData = localData[data[i].serialnum_commodity];
							data[i].title = commodityData.name_commodity;//写入商品名称
							data[i].price = commodityData.money_commodity;//写入商品价格
							// 根据商品名称设置对应的图片
							data[i].image = self.getProductImage(commodityData.name_commodity);
							console.log('商品图片:', data[i].image);
						} else {
							// 如果没有商品数据，使用默认图片
							data[i].image = "../../static/images/51276e00a4890f11936fcc00b81e6367.png";
						}
					}
					self.cartList = data;
					uni.hideLoading();
				}).catch(function(data) {
					console.log('获取购物车数据失败:', data);
				});
			},
			//获取用户购物车信息
			async getCartData() {
				console.log('🛒 获取购物车数据，参数:', {
					account_user: this.userAccount,
					joining_method: 2
				});
				let resultData;
				try {
					resultData = await _findProduct({
						account_user: this.userAccount,
						joining_method: 2
					});
					console.log('✅ 购物车数据返回:', resultData);
				} catch (error) {
					console.error('❌ 获取购物车数据失败:', error);
					throw error; //抛出异常
				}
				if (resultData == undefined || resultData != undefined && resultData.status != 200) {
					console.error('❌ 接口返回异常，状态码:', resultData?.status);
					throw new Error("接口返回异常，位置cart.vue : getCartData");
				}
				console.log('📦 购物车商品数量:', resultData.data?.length || 0);
				return resultData.data;
			},
			//根据商品serialnum_commodity获取商品信息
			async getCommodityData(serialnum_commodity) {
				console.log('🔍 获取商品信息，序列号:', serialnum_commodity);
				let resultData;
				try {
					resultData = await _findCommodity(serialnum_commodity);
					console.log('✅ 商品信息返回:', resultData);
				} catch (error) {
					console.error('❌ 获取商品信息失败:', error);
					throw error; //抛出异常
				}
				if (resultData == undefined || resultData != undefined && resultData.status != 200) {
					console.error('❌ 接口返回异常，状态码:', resultData?.status);
					throw new Error("接口返回异常，位置cart.vue : getCommodityData");
				}
				return resultData.data;
			},
			//滑动组件相关
			upper(e) {
			},
			//滑动组件相关
			lower(e) {
			},
			//滑动组件相关
			scroll(e) {
			},
			//image加载失败时触发，换上失败的图片
			onImageError(obj) {
				obj.image = 'https://img1.baidu.com/it/u=3036696285,3028438343&fm=253&fmt=auto&app=138&f=JPEG';
				//原有图片加载不出来，就替换成这个error图标
			},
			//选中状态处理
			check(item) {
				if (item === 'all') {
					const checked = !this.allChecked
					this.cartList.forEach(item => {
						item.checked = checked;
					})//全选或全不选
					this.allChecked = checked;
				} else {
					item.checked = !item.checked;
				}
				let tempNum = 0;
				this.cartList.forEach(item => {
					item.checked ? tempNum += item.joining_number : null; //重新计算商品总数
				})
				this.num = tempNum;
			},
			//数量变化触发
			numberChange(data) {
				this.cartList[data.index].joining_number = data.number;
				let tempNum = 0;
				this.cartList.forEach(item => {
					item.checked ? tempNum += item.joining_number : null; //重新计算商品总数
				})
				this.num = tempNum;
			},
			//调用删除商品方法
			deleteCartItem(index) {
				let self = this;
				const list = this.cartList;
				const serialnum = list[index].serialnum_commodity;
				this.delete(serialnum).
				then((data) => {
					self.cartList.splice(index, 1); //移除一个元素
					let tempNum = 0;
					self.cartList.forEach(item => {
						item.checked ? tempNum += item.joining_number : null; //重新计算商品总数
					})
					self.num = tempNum;
				}).
				catch((data) => {
					console.log(data);
				});
			}, //真正的删除商品方法
			async delete(serialnum) {
				let resultData;
				try {
					await _deleteByProduct({
						account_user: this.userAccount,
						serialnum_commodity: serialnum,
						joining_method: 2
					}); //调用删除接口
				} catch (error) {
					throw error; //抛出异常
				}
			},
			//计算总价
			calcTotal() {
				const list = this.cartList;
				if (list.length === 0) {
					this.empty = true; //如果列表为空，界面直接为空
					return;
				}
				let total = 0;
				list.forEach(item => {
					if (item.checked == true) {
						total += item.price * item.joining_number;
					}
				})
				this.total = Number(total.toFixed(2)); //算是浮点数修复为两位
			},
			//创建订单
			createOrder() {
				let list = this.cartList;
				let goodsData = [];
				list.forEach(item => {
					if (item.checked) {
						goodsData.push({
							attr_val: item.attr_val,
							number: item.joining_number
						})
					}
				})

				uni.navigateTo({
					url: `/pages/order/createOrder?data=${JSON.stringify({
						goodsData: goodsData
					})}`
				})
				this.$api.msg('跳转下一页 sendData');
			},
			//返回上一页
			back() {
				uni.navigateBack({});
			}
		}
	}
</script>

<style lang='scss'>
	page {
		background-color: #f4f4f4;
	}

	.scroll-Y {
		display: flex;
		position: relative;
		height: 80vh;
	}

	.container {
		padding-bottom: 134upx;

		/* 空白页 */
		.empty {
			position: fixed;
			width: 100%;
			height: 100vh;
			padding-bottom: 100upx;
			display: flex;
			justify-content: center;
			flex-direction: column;
			align-items: center;
			background: #fff;

			image {
				width: 240upx;
				height: 160upx;
				margin-bottom: 30upx;
			}

		.empty-tips {
			display: flex;
			font-size: $font-sm+2upx;
			color: $font-color-disabled;
		}
		}
	}

	/* 购物车列表项 */
	.cart-item {
		display: flex;
		position: relative;
		padding: 30upx 30upx;
		background-color: #ffffff;
		margin: 20upx;
		border-radius: 15upx;

		.image-wrapper {
			width: 230upx;
			height: 230upx;
			flex-shrink: 0;
			position: relative;
		}

		.image-loaded {
			width: 230upx;
			height: 230upx;
			flex-shrink: 0;
			position: relative;

			image {
				border-radius: 8upx;
			}
		}

		.checkbox {
			display: flex;
			z-index: 8;
			//font-size: 44upx;
			line-height: 1;
			padding: 4upx;
			//color: $font-color-disabled;
			//background: #fff;
			//border-radius: 50px;
		}

		.item-right {
			display: flex;
			flex-direction: column;
			flex: 1;
			overflow: hidden;
			position: relative;
			padding-left: 30upx;

			.title,
			.price {
				font-size: $font-base + 2upx;
				color: $font-color-dark;
				height: 40upx;
				line-height: 40upx;
			}

			.attr {
				font-size: $font-sm + 2upx;
				color: $font-color-light;
				height: 50upx;
				line-height: 50upx;
			}

			.price {
				height: 50upx;
				line-height: 50upx;
			}
		}

		.del-btn {
			padding: 4upx 10upx;
			font-size: 34upx;
			height: 50upx;
			color: $font-color-light;
		}
	}

	/* 底部栏 */
	.action-section {
		position: fixed;
		//left: 5vw;
		//right: 5vw;
		bottom: 0upx;
		z-index: 95;
		display: flex;
		align-items: center;
		width: 100vw;
		height: 8vh;
		padding: 0 30upx;
		background: #ffffff;
		//box-shadow: 0 0 20upx 0 rgba(0, 0, 0, .5);
		//border-radius: 16upx;

		.checkbox {
			font-size: 25rpx;
		}

		.clear-btn {
			position: absolute;
			left: 26upx;
			top: 0;
			z-index: 4;
			width: 0;
			height: 52upx;
			line-height: 52upx;
			padding-left: 38upx;
			font-size: $font-base;
			color: #fff;
			background: $font-color-disabled;
			border-radius: 0 50px 50px 0;
			opacity: 0;
			transition: .2s;

			&.show {
				opacity: 1;
				width: 120upx;
			}
		}

		.total-box {
			flex: 1;
			display: flex;
			flex-direction: column;
			text-align: right;
			padding-right: 40upx;

			.price {
				font-size: $font-lg;
				color: $font-color-dark;
			}

			.coupon {
				font-size: $font-sm;
				color: $font-color-light;

				text {
					color: $font-color-dark;
				}
			}
		}

		.confirm-btn {
			padding: 0 38upx;
			margin: 0;
			border-radius: 100px;
			height: 60%;
			line-height: 4.5vh;
			font-size: $font-base + 2upx;
			background: $uni-color-primary;
			box-shadow: 1px 2px 5px #a9a9a9
		}
	}

	/* 复选框选中状态 */
	.action-section .checkbox.checked,
	.cart-item .checkbox.checked {
		color: $uni-color-primary;
	}
</style>